package com.saikei.demoapp.base

import android.app.Application
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.saikei.demoapp.util.Coroutine
import kotlinx.coroutines.CoroutineScope

open class BaseInitVM(app: Application) : AndroidViewModel(app) {

    open fun onLoadBundle(bundle: Bundle?) {
        Log.e("TAG", "日志bundle: ${bundle.toString()}")
    }

    /**
     *
     * mViewModel.asyncLoad {
     *        delay(3000)
     *        "你好"
     *    }.onStart {
     *        Log.e("TAG", "日志: ${"it".toString()}" )
     *    }.onSuccess {
     *        Log.e("TAG", "日志: ${"onSuccess".toString()}" )
     *    }.onError {
     *        Log.e("TAG", "日志: ${"onError".toString()}" )
     *    }.onFinally {
     *        Log.e("TAG", "日志: ${"onFinally".toString()}" )
     *    }
     * @author saikei
     * @date 2025/7/7 10:17
     */
    fun <T> asyncLoad(
        onLoad: suspend CoroutineScope.() -> T
    ): Coroutine<T> {
        return Coroutine(viewModelScope, onLoad).apply {
            async()
        }
    }


    companion object {
        fun <VM : BaseInitVM> factory(app: Application, clazz: Class<VM>): ViewModelProvider.Factory {
            return object : ViewModelProvider.Factory {
                override fun <T : ViewModel> create(modelClass: Class<T>): T {
                    val constructor = clazz.getConstructor(Application::class.java)
                    return constructor.newInstance(app) as T
                }
            }
        }
    }

}
